

#include "../include/server.h"

#define CONNECTNUM 10   //  允许客户端连接数量

/*
int main(int argc,char **argv)
{
	char server_ip[15] = {0};
	int  strP = 0;

       	argumentParse(argc,argv,server_ip,&strP);
	printf("socketInit before strI = %s strP = %d\n",server_ip,strP);
       if(socket_init(server_ip,&strP) < 0)
       {
	       exit(0);
       }

       return 0;
}
*/

/*功能：初始化套接字
 * server_port:服务端口
 * 返回：成功返回套接字，错误返回-1
*/

int socket_init(int server_port)
{
	int listenfd = -1;

    int sockfd = -1;
 
    int opt =  1;

	struct sockaddr_in server_addr;

	//创建套接字
	sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(sockfd < 0)
	{
		printf("create socket error:%s\n",strerror(errno));
        mylog(__func__,__LINE__,ERROR,"Create socket error:%s\n",strerror(errno));
		return -1;
	}

	//初始化网络属性
	memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family = AF_INET;//IPV4
	server_addr.sin_port = htons(server_port);//主机字节序转换为网络字节序
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//指定监听任意ip地址	


	if(setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(const void *)&opt,sizeof(opt)) < 0)//设置端口属性，服务器重启是可再次使用该端口
	{
		printf("set port reuse error:%s\n",strerror(errno));
        mylog(__func__,__LINE__,ERROR,"setsockopt failed:%s\n",strerror(errno));
		return -1;
	}
    
    //绑定端口和ip
	if(bind(sockfd,(const struct sockaddr*)&server_addr,sizeof(server_addr)) < 0)
	{
		printf("bind ip port error:%s\n",strerror(errno));
        mylog(__func__,__LINE__,ERROR,"bind ip and port failed:%s\n",strerror(errno));
		return -1;
	}

    //监听socket，等待客户端连接触发并指定服务器可排队连接的最大数		
    listenfd  = listen(sockfd,CONNECTNUM);
	if(listenfd < 0)
	{
		printf("listen server socket error:%s\n",strerror(errno));
        mylog(__func__,__LINE__,ERROR,"listen server socket failed:%s\n",strerror(errno));
		return -1;
	}

    return sockfd;

}
